package com.example.service;

import com.example.entity.KnowledgeSpace;
import com.example.mapper.KnowledgeSpaceMapper;
import com.example.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class KnowledgeSpaceService {

    private static final Logger logger = LoggerFactory.getLogger(KnowledgeSpaceService.class);

    @Autowired
    private KnowledgeSpaceMapper knowledgeSpaceMapper;

    /**
     * 获取用户可访问的知识空间列表
     */
    public List<KnowledgeSpace> getUserAccessibleSpaces(String username) {
        if (username == null || username.trim().isEmpty()) {
            throw new BusinessException.ValidationException("用户名不能为空");
        }

        try {
            List<KnowledgeSpace> spaces = knowledgeSpaceMapper.getAccessibleSpaces(username);
            logger.debug("获取用户{}可访问的知识空间成功，共{}个", username, spaces.size());
            return spaces;
        } catch (Exception e) {
            logger.error("获取用户可访问空间失败: {}", e.getMessage(), e);
            throw new BusinessException("获取用户可访问空间失败", e);
        }
    }

    /**
     * 根据ID获取知识空间详情
     */
    public KnowledgeSpace getSpaceById(Integer spaceId) {
        if (spaceId == null || spaceId <= 0) {
            throw new BusinessException.ValidationException("空间ID不能为空且必须大于0");
        }

        try {
            KnowledgeSpace space = knowledgeSpaceMapper.getSpaceById(spaceId);
            if (space == null) {
                throw new BusinessException.DataNotFoundException("知识空间不存在");
            }
            return space;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            logger.error("获取知识空间详情失败: {}", e.getMessage(), e);
            throw new BusinessException("获取知识空间详情失败", e);
        }
    }

    /**
     * 创建新的知识空间
     */
    @Transactional(rollbackFor = Exception.class)
    public int createSpace(KnowledgeSpace space) {
        // 设置默认值
        if (space.getSpaceType() == null || space.getSpaceType().trim().isEmpty()) {
            space.setSpaceType("个人"); // 默认为个人空间
        }
        if (space.getVisibility() == null || space.getVisibility().trim().isEmpty()) {
            space.setVisibility("私有"); // 默认为私有
        }

        validateKnowledgeSpace(space);

        try {
            space.setCreatedAt(LocalDateTime.now());
            space.setUpdatedAt(LocalDateTime.now());
            space.setDocumentCount(0);
            space.setIsDeleted(false);

            int result = knowledgeSpaceMapper.insertSpace(space);

            if (result > 0) {
                logger.info("知识空间创建成功: {}", space.getSpaceName());
            }

            return result;
        } catch (Exception e) {
            logger.error("创建知识空间失败: {}", e.getMessage(), e);
            throw new BusinessException("创建知识空间失败", e);
        }
    }

    /**
     * 更新知识空间信息
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateSpace(KnowledgeSpace space) {
        validateKnowledgeSpaceForUpdate(space);

        if (space.getSpaceId() == null || space.getSpaceId() <= 0) {
            throw new BusinessException.ValidationException("空间ID不能为空且必须大于0");
        }

        try {
            // 检查空间是否存在
            KnowledgeSpace existingSpace = knowledgeSpaceMapper.getSpaceById(space.getSpaceId());
            if (existingSpace == null) {
                throw new BusinessException.DataNotFoundException("要更新的知识空间不存在");
            }

            space.setUpdatedAt(LocalDateTime.now());
            int result = knowledgeSpaceMapper.updateSpace(space);

            if (result > 0) {
                logger.info("知识空间更新成功: {}", space.getSpaceName());
            }

            return result;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            logger.error("更新知识空间失败: {}", e.getMessage(), e);
            throw new BusinessException("更新知识空间失败", e);
        }
    }

    /**
     * 删除知识空间
     */
    @Transactional(rollbackFor = Exception.class)
    public int deleteSpace(Integer spaceId) {
        if (spaceId == null || spaceId <= 0) {
            throw new BusinessException.ValidationException("空间ID不能为空且必须大于0");
        }

        try {
            // 检查空间是否存在
            KnowledgeSpace existingSpace = knowledgeSpaceMapper.getSpaceById(spaceId);
            if (existingSpace == null) {
                throw new BusinessException.DataNotFoundException("要删除的知识空间不存在");
            }

            int result = knowledgeSpaceMapper.deleteSpace(spaceId);

            if (result > 0) {
                logger.info("知识空间删除成功: {}", spaceId);
            }

            return result;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            logger.error("删除知识空间失败: {}", e.getMessage(), e);
            throw new BusinessException("删除知识空间失败", e);
        }
    }

    /**
     * 检查用户对空间的访问权限
     */
    public String getUserSpaceRole(Integer spaceId, String username) {
        if (spaceId == null || spaceId <= 0) {
            throw new BusinessException.ValidationException("空间ID不能为空且必须大于0");
        }
        if (username == null || username.trim().isEmpty()) {
            throw new BusinessException.ValidationException("用户名不能为空");
        }

        try {
            return knowledgeSpaceMapper.getUserSpaceRole(spaceId, username);
        } catch (Exception e) {
            logger.error("获取用户空间角色失败: {}", e.getMessage(), e);
            throw new BusinessException("获取用户空间角色失败", e);
        }
    }

    /**
     * 检查用户是否有空间的管理权限
     */
    public boolean hasManagePermission(Integer spaceId, String username) {
        try {
            String role = getUserSpaceRole(spaceId, username);
            return "管理员".equals(role);
        } catch (Exception e) {
            logger.warn("检查管理权限时发生异常: {}", e.getMessage());
            return false;
        }
    }

    /**
     * 检查用户是否有空间的编辑权限
     */
    public boolean hasEditPermission(Integer spaceId, String username) {
        try {
            String role = getUserSpaceRole(spaceId, username);
            return "管理员".equals(role) || "编辑者".equals(role);
        } catch (Exception e) {
            logger.warn("检查编辑权限时发生异常: {}", e.getMessage());
            return false;
        }
    }

    /**
     * 检查用户是否有查看权限
     */
    public boolean hasViewPermission(Integer spaceId, String username) {
        try {
            String role = getUserSpaceRole(spaceId, username);
            return role != null; // 只要有角色就有查看权限
        } catch (Exception e) {
            logger.warn("检查查看权限时发生异常: {}", e.getMessage());
            return false;
        }
    }

    private void validateKnowledgeSpace(KnowledgeSpace space) {
        if (space == null) {
            throw new BusinessException.ValidationException("知识空间信息不能为空");
        }
        if (space.getSpaceName() == null || space.getSpaceName().trim().isEmpty()) {
            throw new BusinessException.ValidationException("空间名称不能为空");
        }
        if (space.getCreatorUsername() == null || space.getCreatorUsername().trim().isEmpty()) {
            throw new BusinessException.ValidationException("创建者不能为空");
        }
        if (space.getSpaceType() == null || space.getSpaceType().trim().isEmpty()) {
            throw new BusinessException.ValidationException("空间类型不能为空");
        }
        if (space.getVisibility() == null || space.getVisibility().trim().isEmpty()) {
            throw new BusinessException.ValidationException("可见性设置不能为空");
        }
        if (space.getSpaceName().length() > 50) {
            throw new BusinessException.ValidationException("空间名称长度不能超过50个字符");
        }
        if (space.getSpaceDescription() != null && space.getSpaceDescription().length() > 500) {
            throw new BusinessException.ValidationException("空间描述长度不能超过500个字符");
        }
    }

    /**
     * 验证知识空间信息（用于更新操作，不验证创建者）
     */
    private void validateKnowledgeSpaceForUpdate(KnowledgeSpace space) {
        if (space == null) {
            throw new BusinessException.ValidationException("知识空间信息不能为空");
        }
        if (space.getSpaceName() == null || space.getSpaceName().trim().isEmpty()) {
            throw new BusinessException.ValidationException("空间名称不能为空");
        }
        // 注意：更新时不验证创建者，因为创建者信息不应该被修改
        if (space.getSpaceType() == null || space.getSpaceType().trim().isEmpty()) {
            throw new BusinessException.ValidationException("空间类型不能为空");
        }
        if (space.getVisibility() == null || space.getVisibility().trim().isEmpty()) {
            throw new BusinessException.ValidationException("可见性设置不能为空");
        }
        if (space.getSpaceName().length() > 50) {
            throw new BusinessException.ValidationException("空间名称长度不能超过50个字符");
        }
        if (space.getSpaceDescription() != null && space.getSpaceDescription().length() > 500) {
            throw new BusinessException.ValidationException("空间描述长度不能超过500个字符");
        }
    }

    /**
     * 宽松的权限验证 - 用于最近访问和收藏功能
     * 允许用户访问曾经有权限访问过的文档
     */
    public boolean hasRelaxedViewPermission(Integer spaceId, String username) {
        // 首先检查当前是否有权限
        if (hasViewPermission(spaceId, username)) {
            return true;
        }

        // 检查是否是公开空间
        KnowledgeSpace space = getSpaceById(spaceId);
        if (space != null && "公开".equals(space.getVisibility())) {
            return true;
        }

        // 对于最近访问和收藏功能，允许访问（因为用户之前已经访问过或收藏过）
        return true;
    }
}
